package com.jandan.ui.client;

import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.Node;
import com.gwtext.client.widgets.menu.BaseItem;
import com.gwtext.client.widgets.menu.Item;
import com.gwtext.client.widgets.menu.Menu;
import com.gwtext.client.widgets.menu.event.BaseItemListenerAdapter;
import com.gwtext.client.widgets.tree.TreeNode;
import com.gwtext.client.widgets.tree.TreePanel;
import com.gwtext.client.widgets.tree.event.TreeNodeListenerAdapter;
import com.gwtext.client.widgets.tree.event.TreePanelListenerAdapter;
import com.jandan.ui.client.service.LessonService;
import com.jandan.ui.client.service.LessonServiceAsync;
import com.jandan.ui.client.util.ClientUtil;
import com.jandan.ui.model.Lesson;
import com.jandan.ui.model.SmallWordLibInfo;

public class MyLessonPanel extends TreePanel {
	private Menu menu;
	private TreeNode ctxNode;
	private ILessonOperator lessonOperate;

	public MyLessonPanel(ILessonOperator lessonOperate) {
		this.lessonOperate = lessonOperate;
		this.setTitle("我的课程");
		this.setAutoScroll(true);
		this.setRootNode(new TreeNode("my lesson"));
		this.setRootVisible(false);

		this.addListener(new TreePanelListenerAdapter() {
			public void onContextMenu(TreeNode node, EventObject e) {
//				int[] xy = e.getXY();
				// MessageBox.alert(node.getId());
				showContextMenu(node, e);
			}
		});
		createComponent();
	}

	public void createComponent() {
		LessonServiceAsync lessonService = LessonService.Util.getInstance();

		lessonService.getLessonList(new AsyncCallback<List<Lesson>>() {

			public void onFailure(Throwable t) {
				// TODO Auto-generated method stub
				System.out.println(t.getMessage());
			}

			public void onSuccess(List<Lesson> lessonList) {
				// TODO Auto-generated method stub
				if (lessonList != null && lessonList.size() > 0) {
					Iterator<Lesson> it = lessonList.iterator();
					while (it.hasNext()) {
						Lesson lesson = it.next();
						addLesson(lesson);
					}
				}
			}

		});
	}

	public void addLesson(final Lesson lesson) {
		if (lesson == null) {
			return;
		}
		
		TreeNode root = this.getRootNode();
		long lessonID = lesson.getLessonID();

		TreeNode newNode = new TreeNode(lesson.getLessonName());
		newNode.setExpanded(false);
		newNode.setId("" + lessonID);
		root.appendChild(newNode);

		TreeNode lessonInfoNode = new TreeNode("统计信息");
		lessonInfoNode.setId(lessonID + "_INFO");
		lessonInfoNode.addListener(new TreeNodeListenerAdapter(){
			@Override
			public void onClick(Node node, EventObject e) {
				// TODO Auto-generated method stub
				lessonOperate.displayLessonInfo(lesson);
			}
		});
		

		newNode.appendChild(lessonInfoNode);

		TreeNode allLibNode = new TreeNode("所学词库");
		allLibNode.setId(lessonID + "_ALLLIB");
		allLibNode.setExpandable(true);
		allLibNode.setExpanded(true);

		newNode.appendChild(allLibNode);

		List<SmallWordLibInfo> smallWordLibList = lesson
				.getSmallWordLibList();

		int size =  smallWordLibList.size();
		SmallWordLibInfo smallWordLib = null;
		StringBuilder sb = null;
		TreeNode lib = null;
		for (int i = 0; i < size; i++) {
			smallWordLib = smallWordLibList.get(i);

			sb = new StringBuilder();
			sb.append("第");
			sb.append(i + 1);
			sb.append("组");
			sb.append("(");
			sb.append(smallWordLib.getStartWord());
			sb.append(" - ");
			sb.append(smallWordLib.getEndWord());
			sb.append(")");
			sb.append("(");
			// sb.append(smallWordLib.getLearnedWordCount());
			// sb.append("/");
			sb.append(smallWordLib.getTotalWordCount());
			sb.append(")");

			lib = new TreeNode(sb.toString());
			lib.setId(lessonID + "_LIB_" + i);

			lib.addListener(new TreeNodeListenerAdapter() {
				@Override
				public void onClick(Node node, EventObject e) {
					// TODO Auto-generated method stub
					String id = node.getId();
					long lessonID = Long.parseLong(id.substring(0, id
							.indexOf("_LIB_")));
					int libNumber = Integer.parseInt(id.substring(id
							.lastIndexOf('_') + 1));

					lessonOperate.study(lessonID, libNumber,
							ClientUtil.STUDY_NEW_WORD);
				}
			});

			allLibNode.appendChild(lib);
		}
	}

	public void deleteLesson(long lessonID) {
		Node node = this.getNodeById("" + lessonID);
		node.remove();
	}

	public TreeMap<Long, String> getLessons() {
		TreeMap<Long, String> map = new TreeMap<Long, String>();

		Node[] lessons = this.getRootNode().getChildNodes();
		TreeNode node = null;
		long id = 0;
		String name = null;
		for (int i = 0; i < lessons.length; i++) {
			node = (TreeNode) lessons[i];
			id = Long.parseLong(node.getId());
			name = node.getText();

			map.put(id, name);
		}

		return map;
	}

	private void showContextMenu(final TreeNode node, EventObject e) {
		final String nodeId = node.getId();
		if (nodeId.indexOf("INFO") >= 0) {

		} else if (nodeId.indexOf("ALLLIB") >= 0) {

		} else if (nodeId.indexOf("LIB_") > 0) { // 小词库节点

			if (menu == null) {
				menu = new Menu();
				Item studyItem = new Item("学习", new BaseItemListenerAdapter() {
					public void onClick(BaseItem item, EventObject e) {
						String id = ctxNode.getId();
						long lessonID = Long.parseLong(id.substring(0, id
								.indexOf("_LIB_")));
						int libNumber = Integer.parseInt(id.substring(id
								.lastIndexOf('_') + 1));

						lessonOperate.study(lessonID, libNumber,
								ClientUtil.STUDY_NEW_WORD);
					}
				});
				studyItem.setId("disable-item");
				menu.addItem(studyItem);

				Item browseItem = new Item("浏览", new BaseItemListenerAdapter() {
					public void onClick(BaseItem item, EventObject e) {
						String id = ctxNode.getId();
						long lessonID = Long.parseLong(id.substring(0, id
								.indexOf("_LIB_")));
						int libNumber = Integer.parseInt(id.substring(id
								.lastIndexOf('_') + 1));

						lessonOperate.browseLearnedWord(lessonID, libNumber);
					}
				});
				browseItem.setId("browse_item");
				menu.addItem(browseItem);

			}

			if (ctxNode != null) {
				ctxNode = null;
			}
			ctxNode = node;

			menu.showAt(e.getXY());
		}
	}
}
